package cn.fresh.xuanyuan.module.infra.service.rule;

import cn.fresh.xuanyuan.module.system.api.social.SocialClientApi;
import cn.hutool.http.HttpUtil;
import com.alibaba.fastjson.JSON;
import com.alibaba.fastjson.JSONObject;
import org.apache.commons.lang3.StringUtils;
import org.springframework.stereotype.Service;

import javax.annotation.Resource;
import java.util.HashMap;
import java.util.Map;

@Service
public class TextRuleService implements ITextRuleService {

    private static final String WX_CHECK_API = "https://api.weixin.qq.com/wxa/msg_sec_check?access_token=";

    @Resource
    private SocialClientApi socialClientApi;

    @Override
    public boolean checkText(String content, Long appId, String openId) {
        String token = socialClientApi.getWxAccessToken(appId).getCheckedData();
        if(StringUtils.isNotBlank(token)) {
            String url = WX_CHECK_API + token;
            Map<String, Object> map = new HashMap<>();
            map.put("content", content);
            map.put("version", 2);
            map.put("scene", 1);
            map.put("openid", openId);
            String res = HttpUtil.post(url, JSON.toJSONString(map));
            if(StringUtils.isNotBlank(res)) {
                JSONObject json = JSON.parseObject(res);
                if(json.getIntValue("errcode") == 0) {
                    JSONObject result = json.getJSONObject("result");
                    if("pass".equals(result.getString("suggest")) && result.getIntValue("label") == 100) {
                        return true;
                    }
                }
            }
        }
        return false;
    }
}
